<template>
  <div class="user-center">
    <div class="container">
      <div class="profile-header">
        <div class="profile-avatar">
          <el-avatar :size="100" :src="userStore.userInfo.avatar || defaultAvatar"></el-avatar>
          <div class="upload-btn">
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <el-button type="primary" size="small" circle>
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-upload>
          </div>
        </div>
        <div class="profile-info">
          <h1 class="username">{{ userStore.userInfo.username }}</h1>
          <p class="email">{{ userStore.userInfo.email }}</p>
        </div>
      </div>
      
      <div class="main-content">
        <el-tabs v-model="activeTab" class="demo-tabs">
          <el-tab-pane label="我的文章" name="articles">
            <div class="article-list" v-loading="loading">
              <div v-if="myArticles.length > 0">
                <div v-for="article in myArticles" :key="article.id" class="article-item">
                  <div class="article-info">
                    <h3 class="article-title">
                      <router-link :to="`/article/${article.id}`">{{ article.title }}</router-link>
                    </h3>
                    <p class="article-desc">{{ formatContent(article.content) }}</p>
                    <div class="article-meta">
                      <span class="meta-item">
                        <el-icon><Clock /></el-icon>
                        {{ formatDate(article.createdAt) }}
                      </span>
                      <div class="tags">
                        <el-tag v-for="tag in article.tags" :key="tag" size="small" effect="plain">{{ tag }}</el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="article-actions">
                    <el-button type="primary" size="small" @click="editArticle(article.id)">
                      <el-icon><Edit /></el-icon> 编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="deleteArticleConfirm(article.id)">
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无文章" />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="账户设置" name="settings">
            <div class="settings-form">
              <el-form
                :model="userForm"
                :rules="userRules"
                ref="userFormRef"
                label-width="100px"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userForm.username" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email" />
                </el-form-item>
                <el-form-item label="更新密码" prop="password">
                  <el-input v-model="userForm.password" type="password" show-password placeholder="不修改请留空" />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="userForm.confirmPassword" type="password" show-password placeholder="不修改请留空" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo" :loading="updating">保存修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="收藏文章" name="favorites">
            <div class="favorite-list" v-loading="loading">
              <div v-if="favoriteArticles.length > 0">
                <div v-for="article in favoriteArticles" :key="article.id" class="article-item">
                  <div class="article-info">
                    <h3 class="article-title">
                      <router-link :to="`/article/${article.id}`">{{ article.title }}</router-link>
                    </h3>
                    <p class="article-desc">{{ formatContent(article.content) }}</p>
                    <div class="article-meta">
                      <span class="meta-item">
                        <el-icon><User /></el-icon>
                        {{ article.author }}
                      </span>
                      <span class="meta-item">
                        <el-icon><Clock /></el-icon>
                        {{ formatDate(article.createdAt) }}
                      </span>
                    </div>
                  </div>
                  <div class="article-actions">
                    <el-button type="danger" size="small" @click="removeFavorite(article.id)">
                      <el-icon><Delete /></el-icon> 取消收藏
                    </el-button>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无收藏文章" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Edit, Delete, Clock, User } from '@element-plus/icons-vue'
import { updateUserInfo as updateUserApi } from '../api/user'

const userStore = useUserStore()
const router = useRouter()
const activeTab = ref('articles')
const loading = ref(false)
const updating = ref(false)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const userFormRef = ref<FormInstance>()
const userForm = reactive({
  username: userStore.userInfo.username || '',
  email: userStore.userInfo.email || '',
  password: '',
  confirmPassword: ''
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  confirmPassword: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (userForm.password && value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 我的文章列表（示例数据）
const myArticles = ref([
  {
    id: '1',
    title: 'Vue3 组合式 API 详解',
    content: '这是一篇关于Vue3组合式API的详细介绍，包括基本概念和使用方法...',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    tags: ['Vue', 'JavaScript', 'Web开发']
  },
  {
    id: '2',
    title: 'TypeScript 高级类型与类型体操',
    content: '本文详细介绍TypeScript中的高级类型用法，以及常见的类型体操技巧...',
    createdAt: new Date(Date.now() - 86400000).toISOString(), // 一天前
    updatedAt: new Date(Date.now() - 86400000).toISOString(),
    tags: ['TypeScript', 'JavaScript']
  }
])

// 收藏的文章列表（示例数据）
const favoriteArticles = ref([
  {
    id: '3',
    title: 'Node.js 性能优化指南',
    content: '本文介绍了Node.js应用的常见性能问题，以及优化技巧和方法...',
    author: '技术大牛',
    createdAt: new Date(Date.now() - 172800000).toISOString(), // 两天前
    updatedAt: new Date(Date.now() - 172800000).toISOString()
  },
  {
    id: '4',
    title: 'Docker 容器化部署实践',
    content: '详细介绍如何使用Docker进行前端和后端项目的容器化部署，提高开发效率...',
    author: '容器专家',
    createdAt: new Date(Date.now() - 259200000).toISOString(), // 三天前
    updatedAt: new Date(Date.now() - 259200000).toISOString()
  }
])

// 处理头像上传
function handleAvatarChange(file: any) {
  // 实际项目中，这里应该处理文件上传
  const fileReader = new FileReader()
  fileReader.onload = (e) => {
    if (e.target && e.target.result) {
      // 更新头像
      const avatarUrl = e.target.result as string
      // 调用更新用户信息API
      ElMessage.success('头像上传成功')
    }
  }
  fileReader.readAsDataURL(file.raw)
}

// 更新用户信息
async function updateUserInfo() {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        updating.value = true
        // 实际项目中，这里调用更新用户信息API
        // const res = await updateUserApi({
        //   username: userForm.username,
        //   email: userForm.email,
        //   password: userForm.password || undefined
        // })
        
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 更新本地用户信息
        userStore.setUserInfo({
          ...userStore.userInfo,
          username: userForm.username,
          email: userForm.email
        })
        
        ElMessage.success('用户信息更新成功')
        
        // 清空密码字段
        userForm.password = ''
        userForm.confirmPassword = ''
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新用户信息失败')
      } finally {
        updating.value = false
      }
    }
  })
}

// 编辑文章
function editArticle(id: string) {
  router.push(`/publish?id=${id}`)
}

// 删除文章确认
function deleteArticleConfirm(id: string) {
  ElMessageBox.confirm('确定要删除该文章吗？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteArticle(id)
  }).catch(() => {})
}

// 删除文章
async function deleteArticle(id: string) {
  try {
    loading.value = true
    // 实际项目中，这里调用删除文章API
    // await deleteArticleApi(id)
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新本地文章列表
    myArticles.value = myArticles.value.filter(article => article.id !== id)
    
    ElMessage.success('文章删除成功')
  } catch (error) {
    console.error('删除文章失败:', error)
    ElMessage.error('删除文章失败')
  } finally {
    loading.value = false
  }
}

// 取消收藏
async function removeFavorite(id: string) {
  try {
    loading.value = true
    // 实际项目中，这里调用取消收藏API
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新本地收藏列表
    favoriteArticles.value = favoriteArticles.value.filter(article => article.id !== id)
    
    ElMessage.success('已取消收藏')
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  } finally {
    loading.value = false
  }
}

// 格式化文章内容（截取摘要）
function formatContent(content: string) {
  if (!content) return ''
  return content.length > 100 ? content.slice(0, 100) + '...' : content
}

// 格式化日期
function formatDate(dateStr: string) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

onMounted(() => {
  // 实际项目中，这里可以获取用户的文章列表和收藏列表
})
</script>

<style scoped lang="scss">
.user-center {
  padding-top: 80px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-header {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  
  .profile-avatar {
    position: relative;
    margin-right: 30px;
    
    .upload-btn {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
  
  .profile-info {
    .username {
      font-size: 24px;
      font-weight: bold;
      margin: 0 0 10px;
      color: #303133;
    }
    
    .email {
      font-size: 16px;
      color: #909399;
      margin: 0;
    }
  }
}

.main-content {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.article-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  
  .article-info {
    flex: 1;
    min-width: 0;
  }
  
  .article-title {
    margin: 0 0 10px;
    font-size: 18px;
    
    a {
      color: #303133;
      text-decoration: none;
      
      &:hover {
        color: #409eff;
      }
    }
  }
  
  .article-desc {
    margin: 0 0 10px;
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
  }
  
  .article-meta {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    font-size: 12px;
    color: #909399;
    
    .meta-item {
      display: flex;
      align-items: center;
      margin-right: 15px;
      
      .el-icon {
        margin-right: 5px;
      }
    }
    
    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
    }
  }
  
  .article-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-left: 20px;
  }
}

.settings-form {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px 0;
}
</style> 